package com.smile.config.hibernate;

import com.alibaba.fastjson.JSON;
import com.smile.config.SpringContextUtil;
import com.smile.config.entity.OperateLog;
import com.smile.config.entity.repository.OperateLogReposotory;
import org.hibernate.EmptyInterceptor;
import org.hibernate.type.Type;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
//https://blog.csdn.net/chenyidong521/article/details/78142430
public class HibernateInterceptor extends EmptyInterceptor {

    private static final long serialVersionUID = 726880039259785420L;


    @Override
    public boolean onLoad(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {
        System.out.println("数据查询");
        return false;
    }

    @Override
    public void onDelete(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {
        System.out.println("删除数据");
    }

    @Override
    @Transactional
    public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) {
        System.out.println("修改数据");

        OperateLogReposotory operateLogReposotory = SpringContextUtil.getBean("operateLogReposotory", OperateLogReposotory.class);

        OperateLog operateLog = new OperateLog();
        operateLog.setContent("修改数据:"+ JSON.toJSONString(entity));
        operateLogReposotory.save(operateLog);

          /*Random random = new Random();

          if (entity instanceof SuperBaseEntity) {
              for (int index = 0, length= propertyNames.length; index < length; index++) {
                  if("lastUpdateUserId".equals(propertyNames[index])){
                      currentState[index] = Long.parseLong(random.nextInt(100)+"");
                  }
              }
              return true;
          }*/

        return false;
    }

    @Override
    public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {
        System.out.println("保存数据");
        return false;
    }

}
